package com.example.demo.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.web.server.ServerWebExchange;


import com.example.demo.context.GatewayContext;

import reactor.core.publisher.Mono;

/**
  * Created on 2019-07-16
 */
public class RequestLogGatewayFilterFactory extends AbstractGatewayFilterFactory {
    private static final Logger logger = LoggerFactory.getLogger(RequestLogGatewayFilterFactory.class);

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> filter(exchange, chain);
    }

    private Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.debug("==========开始执行filter[打印request日志]==========");


        GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.GATEWAY_CONTEXT_KEY);
        if (gatewayContext != null) {

            logger.info(gatewayContext.toString());
        }


        return chain.filter(exchange);
    }


}
